﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using DiscoveryLogic.Common.Utilities;
using DiscoveryLogic.Common.Utilities.OpenXml;
using DiscoveryLogic.DataViz.NetworkDiagram.NetworkData;
using EntityType=DiscoveryLogic.DataViz.NetworkDiagram.NetworkData.EntityType;

namespace DiscoveryLogic.DataViz.NetworkDiagram
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="net"></param>
    public delegate void OnNetworkCreated(Network net);

    /// <summary>
    /// 
    /// </summary>
    public partial class NewNetworkData : Form
    {
        /// <summary>
        /// 
        /// </summary>
        public event OnNetworkCreated NetworkCreated;
        /// <summary>
        /// 
        /// </summary>
        public NewNetworkData()
        {
            InitializeComponent();
        }

        private void NewNetworkData_Load(object sender, EventArgs e)
        {
            Assembly assembly = this.GetType().Assembly;
            Type[] types = assembly.GetTypes();
            this.cbo_DistanceCalc.Items.Clear();
            foreach(Type type in types)
            {
                if(type.GetInterface(typeof(ILinkDistanceCalculator).FullName)!= null)
                {
                    this.cbo_DistanceCalc.Items.Add(type.FullName);
                }
            }
            this.cbo_NodeTypes.Items.Clear();
            for(int i=0;i<=3;i++)
            {
                EntityType entityType = (EntityType) i;
                this.cbo_NodeTypes.Items.Add(entityType.ToString());
            }
            this.cbo_LinkTypes.Items.Clear();
            for(int i=0;i<=2;i++)
            {
                LinkType linkType = (LinkType) i;
                this.cbo_LinkTypes.Items.Add(linkType.ToString());
            }
            this.cbo_LinkMethod.Items.Clear();
            for(int i=0;i<=8;i++)
            {
                LinkMethod method = (LinkMethod) i;
                this.cbo_LinkMethod.Items.Add(method.ToString());
            }
        }

        

        #region src data
        private void rd_Db_CheckedChanged(object sender, EventArgs e)
        {
            SetDataSourceType srcType = SetDataSourceType.DB;
            if (this.rd_Db.Checked)
                srcType = SetDataSourceType.DB;
            else if (this.rd_Xml.Checked)
                srcType = SetDataSourceType.XML;
            else if (this.rd_Excel.Checked)
                srcType = SetDataSourceType.ExcelFile;
            this.UpdateDataSourceType(srcType);
        }

        private void rd_Xml_CheckedChanged(object sender, EventArgs e)
        {
            SetDataSourceType srcType = SetDataSourceType.DB;
            if (this.rd_Db.Checked)
                srcType = SetDataSourceType.DB;
            else if (this.rd_Xml.Checked)
                srcType = SetDataSourceType.XML;
            else if (this.rd_Excel.Checked)
                srcType = SetDataSourceType.ExcelFile;
            this.UpdateDataSourceType(srcType);
        }

        private void rd_Excel_CheckedChanged(object sender, EventArgs e)
        {
            SetDataSourceType srcType = SetDataSourceType.DB;
            if (this.rd_Db.Checked)
                srcType = SetDataSourceType.DB;
            else if (this.rd_Xml.Checked)
                srcType = SetDataSourceType.XML;
            else if (this.rd_Excel.Checked)
                srcType = SetDataSourceType.ExcelFile;
            this.UpdateDataSourceType(srcType);
        }

        private void UpdateDataSourceType(SetDataSourceType srcType)
        {
            if (srcType == SetDataSourceType.DB)
            {
                this.lbl_DataSourcePath.Text = "Connection:";
                this.lbl_RecordPath.Text = "Table:";
                this.btn_BrowseDataSource.Visible = false;
            }
            else if (srcType == SetDataSourceType.XML || srcType == SetDataSourceType.ExcelFile)
            {
                this.lbl_DataSourcePath.Text = "Source file:";
                this.lbl_RecordPath.Text = "Record path:";
                this.btn_BrowseDataSource.Visible = true;
            }
        }

        private void btn_BrowseDataSource_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            if (this.rd_Xml.Checked)
            {
                dlg.Filter = "Xml files(*.find;*.xml)|*.find;*.xml|All files(*.*)|*.*";
            }
            else if (this.rd_Excel.Checked)
            {
                dlg.Filter = "Excel files(*.xls;*.xlsx)|*.xls;*.xlsx|All files(*.*)|*.*";
            }
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                this.txt_DataSourcePath.Text = dlg.FileName;
                if(this.rd_Xml.Checked || this.rd_Excel.Checked)
                    this.UpdateRecordPaths();
            }
        }

        private void cbo_RecordPath_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbo_RecordPath.SelectedIndex < 0)
                return;
            this.cbo_Key.Items.Clear();
            this.cbo_TitleFields.Items.Clear();
            this.cbo_TimeStampField.Items.Clear();
            this.cbo_LinkFrom.Items.Clear();
            this.cbo_LinkTo.Items.Clear();
            this.dv_FieldBindings.Rows.Clear();
            Dictionary<string,SimpleDataType> fieldDataTypes = this.GetFields();
            if (fieldDataTypes != null && fieldDataTypes.Count > 0)
            {
                foreach (string colName in fieldDataTypes.Keys)
                {
                    this.cbo_Key.Items.Add(colName);
                    this.cbo_TitleFields.Items.Add(colName);
                    this.cbo_TimeStampField.Items.Add(colName);
                    this.cbo_LinkFrom.Items.Add(colName);
                    this.cbo_LinkTo.Items.Add(colName);

                    DataGridViewRow dr = new DataGridViewRow();
                    DataGridViewCheckBoxCell cellSelect = new DataGridViewCheckBoxCell();
                    cellSelect.Value = true;
                    dr.Cells.Add(cellSelect);
                    DataGridViewTextBoxCell cellSrcField = new DataGridViewTextBoxCell();
                    cellSrcField.Value = colName;
                    dr.Cells.Add(cellSrcField);
                    DataGridViewTextBoxCell cellTgtField=new DataGridViewTextBoxCell();
                    cellTgtField.Value = colName;
                    dr.Cells.Add(cellTgtField);
                    DataGridViewComboBoxCell cellDataType=new DataGridViewComboBoxCell();
                    for(int i=0;i<=9;i++)
                    {
                        SimpleDataType dataType = (SimpleDataType) i;
                        cellDataType.Items.Add(dataType.ToString());
                    }
                    cellDataType.Value = fieldDataTypes[colName].ToString();
                    dr.Cells.Add(cellDataType);
                    DataGridViewCheckBoxCell cellFilterable=new DataGridViewCheckBoxCell();
                    cellFilterable.Value = true;
                    dr.Cells.Add(cellFilterable);
                    DataGridViewCheckBoxCell cellLinkable=new DataGridViewCheckBoxCell();
                    cellLinkable.Value = true;
                    dr.Cells.Add(cellLinkable);
                    this.dv_FieldBindings.Rows.Add(dr);
                }

                if(this.cbo_DistanceCalc.SelectedIndex>=0)
                {
                    string typeName = this.cbo_DistanceCalc.SelectedItem.ToString();
                    Assembly assembly = this.GetType().Assembly;
                    Type type = assembly.GetType(typeName);
                    if (type.GetInterface(typeof(ILinkDistanceCalculator).FullName) != null)
                    {
                        ILinkDistanceCalculator calc = (ILinkDistanceCalculator)Activator.CreateInstance(type);
                        List<string> fieldNames=new List<string>();
                        fieldNames.AddRange(fieldDataTypes.Keys);
                        this.PopulateDistanceCalcArgFields(calc, fieldNames);
                    }
                }
            }
        }

        private Dictionary<string,SimpleDataType> GetFields()
        {
            Dictionary<string, SimpleDataType> fieldDataTypes = new Dictionary<string, SimpleDataType>();
            if (this.rd_Db.Checked && !string.IsNullOrEmpty(this.txt_DataSourcePath.Text))
            {
                string tblName = this.cbo_RecordPath.SelectedItem.ToString();
                TableColumn[] cols = DbUtil.GetTableColumns(DataProviderType.MSSQL, this.txt_DataSourcePath.Text, string.Empty,
                                                            tblName);
                if (cols != null && cols.Length > 0)
                {
                    foreach (TableColumn col in cols)
                    {
                        fieldDataTypes.Add(col.ColumnName, SimpleDataTypeUtil.ToSimpleDataType(col.DbType));
                    }
                }
            }
            else if (this.rd_Xml.Checked && !string.IsNullOrEmpty(this.txt_DataSourcePath.Text))
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(this.txt_DataSourcePath.Text);
                XmlNodeList xNodes = xDoc.SelectNodes(this.cbo_RecordPath.SelectedItem.ToString());
                if (xNodes != null && xNodes.Count > 0)
                {
                    XmlNode xNode = xNodes[0];
                    foreach (XmlAttribute attr in xNode.Attributes)
                    {
                        fieldDataTypes.Add(attr.Name, SimpleDataType.TextType);
                    }
                }
            }
            else if (this.rd_Excel.Checked && !string.IsNullOrEmpty(this.txt_DataSourcePath.Text))
            {
                string sheetName = this.cbo_RecordPath.SelectedItem.ToString();
                // List<string> colHeaders = ExcelFileHelper.ReadColumnHeaders(this.txt_DataSourcePath.Text, sheetName);
                List<string> colHeaders = ExcelReader.ReadColumnHeaders(this.txt_DataSourcePath.Text, sheetName);
                if (colHeaders != null && colHeaders.Count > 0)
                {
                    foreach (string colName in colHeaders)
                    {
                        fieldDataTypes.Add(colName, SimpleDataType.TextType);
                    }
                }
            }

            return fieldDataTypes;
        }

        private void UpdateRecordPaths()
        {
            if (this.rd_Db.Checked && !string.IsNullOrEmpty(this.txt_DataSourcePath.Text))
            {
                this.cbo_RecordPath.Items.Clear();
                string[] tblNames = DbUtil.GetTableNames(DataProviderType.MSSQL, string.Empty, this.txt_DataSourcePath.Text);
                if (tblNames != null && tblNames.Length > 0)
                {
                    foreach (string tblName in tblNames)
                    {
                        this.cbo_RecordPath.Items.Add(tblName);
                    }
                }
            }
            else if (this.rd_Xml.Checked && !string.IsNullOrEmpty(this.txt_DataSourcePath.Text))
            {
                XmlTextReader xReader = new XmlTextReader(File.OpenRead(this.txt_DataSourcePath.Text));
                this.cbo_RecordPath.Items.Clear();
                List<string> allPaths = new List<string>();
                int lastDepth = -1;
                string lastNodeName = string.Empty;
                Stack<string> elementNames = new Stack<string>();
                while (xReader.Read())
                {
                    if (xReader.NodeType == XmlNodeType.Element)
                    {
                        int currentDepth = xReader.Depth;
                        if (currentDepth > lastDepth)
                        {
                            lastDepth = currentDepth;
                            lastNodeName = xReader.Name;
                            elementNames.Push(lastNodeName);
                            string xPath = this.GetXPath(elementNames);
                            if (!allPaths.Contains(xPath))
                                allPaths.Add(xPath);
                        }
                        else if (currentDepth == lastDepth)
                        {
                            if (xReader.Name == lastNodeName)
                                continue;
                            else
                            {
                                lastNodeName = xReader.Name;
                                if (elementNames.Count > 0)
                                    elementNames.Pop();
                                elementNames.Push(lastNodeName);
                                string xPath = this.GetXPath(elementNames);
                                if (!allPaths.Contains(xPath))
                                    allPaths.Add(xPath);
                            }
                        }
                        else
                        {
                            lastDepth = xReader.Depth;
                            lastNodeName = xReader.Name;
                            while (elementNames.Count > xReader.Depth)
                                elementNames.Pop();
                            elementNames.Push(lastNodeName);
                            string xPath = this.GetXPath(elementNames);
                            if (!allPaths.Contains(xPath))
                                allPaths.Add(xPath);
                        }
                    }
                    else if (xReader.NodeType == XmlNodeType.EndElement)
                    {

                    }
                }
                xReader.Close();
                foreach (string xPath in allPaths)
                {
                    this.cbo_RecordPath.Items.Add(xPath);
                }
            }
            else if (this.rd_Excel.Checked && !string.IsNullOrEmpty(this.txt_DataSourcePath.Text))
            {
                //List<string> sheetNames = ExcelFileHelper.GetWorksheetNames(this.txt_DataSourcePath.Text);
                List<string> sheetNames = ExcelReader.GetWorksheetNames(this.txt_DataSourcePath.Text);
                this.cbo_RecordPath.Items.Clear();
                foreach (string sheetName in sheetNames)
                {
                    this.cbo_RecordPath.Items.Add(sheetName);
                }
            }
        }

        private void btn_RefreshRecordPaths_Click(object sender, EventArgs e)
        {
            this.UpdateRecordPaths();
        }

        private string GetXPath(Stack<string> elementNames)
        {
            string[] elementNamesCopy = elementNames.ToArray();
            string path = string.Empty;
            for (int i = elementNamesCopy.Length - 1; i >= 0; i--)
            {
                if (path.Length > 0)
                    path += "/";
                path += elementNamesCopy[i];
            }
            return path;
        }
        #endregion

        private void btn_OK_Click(object sender, EventArgs e)
        {
        	Network network = new Network();

            // meta data
            network.NetworkName = this.txt_NetworkName.Text;
            network.EntityType = (EntityType) this.cbo_NodeTypes.SelectedIndex;
            network.IsInferred = this.ck_InferredLink.Checked;
            network.RelationType = (LinkType) this.cbo_LinkTypes.SelectedIndex;

            // provider
            SetDataProvider provider = new SetDataProvider();
            provider.SourceType = SetDataSourceType.DB;
            if (rd_Xml.Checked)
                provider.SourceType = SetDataSourceType.XML;
            else if (rd_Excel.Checked)
                provider.SourceType = SetDataSourceType.ExcelFile;
            provider.DataSourcePath = this.txt_DataSourcePath.Text;
            provider.RecordListPath = this.cbo_RecordPath.Text;
            provider.KeyFieldName = this.cbo_Key.Text;
            provider.LabelField = this.cbo_TitleFields.Text;
            provider.FieldPaths = new Dictionary<string, string>();
            foreach (DataGridViewRow dr in this.dv_FieldBindings.Rows)
            {
                if (!dr.IsNewRow && dr.Cells[0].Value != null && dr.Cells[1].Value != null)
                {
                    bool selected = bool.Parse(dr.Cells[0].Value.ToString());
                    if(!selected)
                        continue;
                    string fieldName = dr.Cells[1].Value.ToString();
                    string propName = dr.Cells[2].Value.ToString();
                    provider.FieldPaths.Add(fieldName, propName);
                }
            }
            network.DataProvider = provider;
            
            // distance 
            Assembly assembly = this.GetType().Assembly;
            network.DistanceCalculator = null;
            if (!string.IsNullOrEmpty(this.cbo_DistanceCalc.Text))
            {
                Type distanceCalcType = assembly.GetType(this.cbo_DistanceCalc.Text);
                if (distanceCalcType != null)
                {
                    network.DistanceCalculator = (ILinkDistanceCalculator)Activator.CreateInstance(distanceCalcType);
                }
            }
            network.AttractingForce = (double) this.num_Attract.Value;
            network.RepellingForce = (double) this.num_Repel.Value;

            // NetData
            NetworkDataObject netDO=new NetworkDataObject();
            netDO.DistanceCalcArgumentMappings=new Dictionary<string, string>();
            foreach(DataGridViewRow dr in this.dv_DistCalcArgMapping.Rows)
            {
                if(!dr.IsNewRow && dr.Cells[0].Value !=null && dr.Cells[1].Value !=null)
                {
                    string argName = dr.Cells[0].Value.ToString();
                    string fieldName = dr.Cells[1].Value.ToString();
                    netDO.DistanceCalcArgumentMappings.Add(fieldName,argName);
                }
            }
            netDO.EntityTypeName = this.txt_EntityTypeName.Text;
            netDO.FieldDataTypes=new Dictionary<string, SimpleDataType>();
            netDO.FieldNameMappings=new Dictionary<string, string>();
            netDO.FilterableFields=new List<string>();
            netDO.LabelFieldName = this.cbo_TitleFields.Text;
            netDO.TimeStampField = this.cbo_TimeStampField.Text;
            netDO.LinkableFields=new List<string>();
            netDO.PkFieldName = this.cbo_Key.Text;
            netDO.SelfLinkFromFields = new List<string>();
            if (this.cbo_LinkFrom.SelectedIndex >= 0)
                netDO.SelfLinkFromFields.Add(this.cbo_LinkFrom.Text);
            netDO.SelfLinkToFields=new List<string>();
            if (this.cbo_LinkTo.SelectedIndex >= 0)
                netDO.SelfLinkToFields.Add(this.cbo_LinkTo.Text);
            netDO.SelfLinkMethod = LinkMethod.Equals;
            if(this.cbo_LinkMethod.SelectedIndex>=0)
                netDO.SelfLinkMethod = (LinkMethod) this.cbo_LinkMethod.SelectedIndex;
            netDO.IsLinkDirectional = this.ck_Directional.Checked;
            foreach(DataGridViewRow dr in this.dv_FieldBindings.Rows)
            {
                if(!dr.IsNewRow)
                {
                    DataGridViewCheckBoxCell cellSelect = (DataGridViewCheckBoxCell) dr.Cells[0];
                    bool selected = bool.Parse(cellSelect.Value.ToString());
                    if(!selected)
                        continue;

                    string srcField = dr.Cells[1].Value.ToString();
                    string tgtField = dr.Cells[2].Value.ToString();
                    string dbTypeStr = dr.Cells[3].Value.ToString();
                    SimpleDataType dbType = (SimpleDataType) Enum.Parse(typeof (SimpleDataType), dbTypeStr);
                    bool filterable = bool.Parse(dr.Cells[4].Value.ToString());
                    bool linkable = bool.Parse(dr.Cells[5].Value.ToString());
                    netDO.FieldNameMappings.Add(srcField,tgtField);
                    netDO.FieldDataTypes.Add(tgtField,dbType);
                    if(filterable)
                        netDO.FilterableFields.Add(tgtField);
                    if(linkable)
                        netDO.LinkableFields.Add(tgtField);
                }
            }
            network.NetData = netDO;

            try
            {
                network.Save();
                if (this.NetworkCreated != null)
                    this.NetworkCreated(network);
                this.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        #region distance 
        private void cbo_DistanceCalc_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(this.cbo_RecordPath.SelectedIndex>=0 && this.cbo_DistanceCalc.SelectedIndex>=0)
            {
                Dictionary<string,SimpleDataType> fieldDataTypes = this.GetFields();
                if (fieldDataTypes == null || fieldDataTypes.Count == 0)
                    return;

                string typeName = this.cbo_DistanceCalc.SelectedItem.ToString();
                Assembly assembly = this.GetType().Assembly;
                Type type = assembly.GetType(typeName);
                if (type.GetInterface(typeof(ILinkDistanceCalculator).FullName) != null)
                {
                    ILinkDistanceCalculator calc = (ILinkDistanceCalculator) Activator.CreateInstance(type);
                    List<string> fieldNames=new List<string>();
                    fieldNames.AddRange(fieldDataTypes.Keys);
                    this.PopulateDistanceCalcArgFields(calc, fieldNames);
                }
            }
        }

        private void PopulateDistanceCalcArgFields(ILinkDistanceCalculator calc, List<string> fields)
        {
            this.dv_DistCalcArgMapping.Rows.Clear();
            foreach(string reqArgName in calc.RequiredArguments.Keys)
            {
                DataGridViewRow dr = new DataGridViewRow();
                DataGridViewTextBoxCell cellArg=new DataGridViewTextBoxCell();
                cellArg.Value = reqArgName;
                dr.Cells.Add(cellArg);

                DataGridViewComboBoxCell cellField=new DataGridViewComboBoxCell();
                foreach(string fieldName in fields)
                {
                    cellField.Items.Add(fieldName);
                }
                dr.Cells.Add(cellField);

                this.dv_DistCalcArgMapping.Rows.Add(dr);
            }
        }
        #endregion
    }
}
